﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestLock
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread[] threads=new Thread[5];
            TestLock t=new TestLock(1000);//公用一个对象时，会出现 多线程同时修改一个数值，达到未预期效果，产生错误
            for (int i = 0; i < 5; i++)
            {
                threads[i]=new Thread(new ThreadStart(t.WithTest));

            }
            for (int i = 0; i < 5; i++)
            {
                threads[i].Start();
            }
            Console.ReadLine();
        }
    }

    public class TestLock
    {
        private object myLock=new object();
        int printValue;
        Random r=new Random();
        public TestLock(int value)
        {
            printValue = value;
        }

        int ChangeValue(int currentValue)
        {
            if (printValue<0)
            {
                Console.WriteLine("a:" + printValue + "    b:" + currentValue + "   r:" + (printValue - currentValue) + "   entercase:zero");
                return 0;
            }
            lock (myLock)
            {
                if (printValue > currentValue)
                {
                    Console.WriteLine("a:" + printValue + "    b:" + currentValue + "   r:" + (printValue - currentValue) + "   entercase:one");
                    printValue = printValue - currentValue;
                    return printValue - currentValue;
                }
                else
                {
                    Console.WriteLine("a:" + printValue + "    b:" + currentValue + "   entercase:two");
                    return 0;
                }
            }
            
        }

        public void WithTest()
        {
            for (int i = 0; i < 100; i++)
            {
                ChangeValue(r.Next(1, 100));
            }
        }
    }
}
